<?php

namespace app\admin\controller;

use app\admin\model\Category;
use app\admin\model\User;
use app\common\LogService;
use think\facade\Log;
use think\facade\Session;

class Login
{
    public function index()
    {
        return view();
    }
    public function doLog()
    {
        $param = input('post.');
        $qq = isset($param['qq']) ? $param['qq'] : '';
        $password = isset($param['password']) ? $param['password'] : '';
        $vercode = isset($param['vercode']) ? $param['vercode'] : '';
        $recordLog = function ($status, $message, $userId = 0) use ($qq) {
            LogService::record(
                user_id: $userId,
                name: '管理员登录',
                content: ['reason' => $message],
                user_type: 2,
                status: $status // 0表示失败，1版主示成功
            );
        };

        if (!captcha_check($vercode)) {
            $recordLog(0, "验证码错误 (QQ: {$qq})");
            return error('验证码错误', 230);
        }

        $user = User::where(['qq' => $qq])->find();
        if (!$user) {
            $recordLog(0, "管理员不存在 (QQ: {$qq})");
            return error('管理员不存在');
        }

        if ($user['status'] == 2) {
            $recordLog(0, "账户已被封禁", $user['id']);
            return error('该账户已被封禁');
        }

        if (encrypt_pwd($password) != $user['password']) {
            $recordLog(0, "密码错误", $user['id']);
            return error('密码错误');
        }
        if ($user['role'] != 0 && $user['role'] != 2) {
            return error('查找不到管理员数据');
        }
        $data =  ['id' => $user['id'], 'role' => $user['role']];
        Session::set('admin', $data);
        User::where(['status' => 1, 'qq' => $qq])->update(['last_time' => time(), 'last_login_ip' => getIP()]);
        // 记录成功登录
        $recordLog(1, '', $user['id']);
        return success('', $data);
    }
    public function logout()
    {
        if (Session::has('admin')) {
            LogService::record(
                user_id: getAdminSessionVal(),
                name: '退出登录',
                user_type: 2
            );
            Session::set('admin', null);
            Session::destroy();
            return success();
        }
    }
}
